{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2024-09-24T00:32:07.243756Z",
     "start_time": "2024-09-24T00:32:07.223147Z"
    }
   },
   "source": [
    "# 数据处理、数据评分相关库\n",
    "import pandas as pd \n",
    "import numpy as np\n",
    "\n",
    "# 画图\n",
    "import matplotlib\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from scipy import stats\n",
    "%matplotlib inline\n",
    "plt.rcParams['font.sans-serif']='SimHei'# 设置中文显示\n",
    "plt.rcParams['font.size']=14 # 设置字体大小\n",
    "matplotlib.rcParams['axes.unicode_minus'] = False # 解决负号问题\n",
    "\n",
    "#忽略警号 \n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")"
   ],
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-24T00:32:08.776998Z",
     "start_time": "2024-09-24T00:32:07.245733Z"
    }
   },
   "cell_type": "code",
   "source": [
    "data = pd.read_csv('data.csv')\n",
    "data.fillna(0,inplace=True)"
   ],
   "id": "48dfbefd82d18f06",
   "outputs": [],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-24T00:32:08.944120Z",
     "start_time": "2024-09-24T00:32:08.778004Z"
    }
   },
   "cell_type": "code",
   "source": [
    "train = data[data['origin']=='train'].drop(['origin'],axis=1)\n",
    "test = data[data['origin']=='test'].drop(['label','origin'],axis=1)"
   ],
   "id": "23eb66158dfd1c9d",
   "outputs": [],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-24T00:32:08.968358Z",
     "start_time": "2024-09-24T00:32:08.945084Z"
    }
   },
   "cell_type": "code",
   "source": "X,Y = train.drop(['label'],axis=1),train['label'] ",
   "id": "c349a292813e11c2",
   "outputs": [],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-24T00:32:09.642118Z",
     "start_time": "2024-09-24T00:32:08.969362Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "train_x,valid_x,train_y,valid_y = train_test_split(X,Y,test_size=0.2)"
   ],
   "id": "3aada7f9a00b06b5",
   "outputs": [],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-24T00:32:10.145835Z",
     "start_time": "2024-09-24T00:32:09.643123Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from sklearn.naive_bayes import GaussianNB\n",
    "from sklearn.model_selection import cross_val_score\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.model_selection import GridSearchCV\n",
    "from sklearn.feature_selection import SelectKBest\n",
    "from sklearn.feature_selection import mutual_info_classif\n",
    "from xgboost import XGBClassifier\n",
    "from sklearn.metrics import roc_auc_score, roc_curve, accuracy_score, confusion_matrix, log_loss, auc, \\\n",
    "    precision_recall_curve\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.model_selection import train_test_split"
   ],
   "id": "b673789ea721391c",
   "outputs": [],
   "execution_count": 6
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-24T00:33:10.075374Z",
     "start_time": "2024-09-24T00:32:10.146840Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 使用默认参数建模\n",
    "model = RandomForestClassifier()\n",
    "model.fit(train_x,train_y)"
   ],
   "id": "f59cf587b12f659d",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "RandomForestClassifier()"
      ],
      "text/html": [
       "<style>#sk-container-id-1 {color: black;background-color: white;}#sk-container-id-1 pre{padding: 0;}#sk-container-id-1 div.sk-toggleable {background-color: white;}#sk-container-id-1 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-1 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-1 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-1 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-1 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-1 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-1 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-1 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-1 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-1 div.sk-item {position: relative;z-index: 1;}#sk-container-id-1 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-1 div.sk-item::before, #sk-container-id-1 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-1 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-1 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-1 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-1 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-1 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-1 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-1 div.sk-label-container {text-align: center;}#sk-container-id-1 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-1 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>RandomForestClassifier()</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" checked><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">RandomForestClassifier</label><div class=\"sk-toggleable__content\"><pre>RandomForestClassifier()</pre></div></div></div></div></div>"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-24T00:33:12.334223Z",
     "start_time": "2024-09-24T00:33:10.076350Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# evaluate model\n",
    "auc_rf = roc_auc_score(valid_y,model.predict_proba(valid_x)[:,1])\n",
    "print('accuracy：',model.score(valid_x,valid_y))\n",
    "print('roc_auc：',auc_rf)"
   ],
   "id": "a9e02aca13830ade",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "accuracy： 0.9383589212811224\n",
      "roc_auc： 0.643191158865367\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-24T00:33:12.338475Z",
     "start_time": "2024-09-24T00:33:12.335207Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 调参\n",
    "model = RandomForestClassifier()\n",
    "params = {\"n_estimators\":[50,100,150],  \n",
    "          \"max_depth\":[5,10,15,20],\n",
    "          \"min_samples_split\":[5,10,12,18],\n",
    "          \"min_samples_leaf\":[1,3,26]\n",
    "         }\n",
    "\n",
    "grid_search = GridSearchCV(model,params,cv = 3,scoring = \"roc_auc\")"
   ],
   "id": "fbc93db0f604ab67",
   "outputs": [],
   "execution_count": 9
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-24T03:06:47.296809Z",
     "start_time": "2024-09-24T00:33:12.338996Z"
    }
   },
   "cell_type": "code",
   "source": "grid_search.fit(train_x,train_y)",
   "id": "8b54490ea51f4a9c",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "GridSearchCV(cv=3, estimator=RandomForestClassifier(),\n",
       "             param_grid={'max_depth': [5, 10, 15, 20],\n",
       "                         'min_samples_leaf': [1, 3, 26],\n",
       "                         'min_samples_split': [5, 10, 12, 18],\n",
       "                         'n_estimators': [50, 100, 150]},\n",
       "             scoring='roc_auc')"
      ],
      "text/html": [
       "<style>#sk-container-id-2 {color: black;background-color: white;}#sk-container-id-2 pre{padding: 0;}#sk-container-id-2 div.sk-toggleable {background-color: white;}#sk-container-id-2 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-2 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-2 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-2 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-2 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-2 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-2 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-2 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-2 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-2 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-2 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-2 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-2 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-2 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-2 div.sk-item {position: relative;z-index: 1;}#sk-container-id-2 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-2 div.sk-item::before, #sk-container-id-2 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-2 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-2 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-2 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-2 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-2 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-2 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-2 div.sk-label-container {text-align: center;}#sk-container-id-2 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-2 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-2\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>GridSearchCV(cv=3, estimator=RandomForestClassifier(),\n",
       "             param_grid={&#x27;max_depth&#x27;: [5, 10, 15, 20],\n",
       "                         &#x27;min_samples_leaf&#x27;: [1, 3, 26],\n",
       "                         &#x27;min_samples_split&#x27;: [5, 10, 12, 18],\n",
       "                         &#x27;n_estimators&#x27;: [50, 100, 150]},\n",
       "             scoring=&#x27;roc_auc&#x27;)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-2\" type=\"checkbox\" ><label for=\"sk-estimator-id-2\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">GridSearchCV</label><div class=\"sk-toggleable__content\"><pre>GridSearchCV(cv=3, estimator=RandomForestClassifier(),\n",
       "             param_grid={&#x27;max_depth&#x27;: [5, 10, 15, 20],\n",
       "                         &#x27;min_samples_leaf&#x27;: [1, 3, 26],\n",
       "                         &#x27;min_samples_split&#x27;: [5, 10, 12, 18],\n",
       "                         &#x27;n_estimators&#x27;: [50, 100, 150]},\n",
       "             scoring=&#x27;roc_auc&#x27;)</pre></div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-3\" type=\"checkbox\" ><label for=\"sk-estimator-id-3\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">estimator: RandomForestClassifier</label><div class=\"sk-toggleable__content\"><pre>RandomForestClassifier()</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-4\" type=\"checkbox\" ><label for=\"sk-estimator-id-4\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">RandomForestClassifier</label><div class=\"sk-toggleable__content\"><pre>RandomForestClassifier()</pre></div></div></div></div></div></div></div></div></div></div>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 10
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-24T03:06:47.316745Z",
     "start_time": "2024-09-24T03:06:47.302791Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 调参后的最优参数结果\n",
    "display(grid_search.best_params_)\n",
    "display(grid_search.best_score_)"
   ],
   "id": "9bd81cf72fb4d6b",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'max_depth': 15,\n",
       " 'min_samples_leaf': 26,\n",
       " 'min_samples_split': 5,\n",
       " 'n_estimators': 150}"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "0.6656395922957867"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-24T03:07:22.622301Z",
     "start_time": "2024-09-24T03:06:47.318738Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# evaluate the model \n",
    " \n",
    "# 二次计算时，直接使用最优参数建模\n",
    "model = RandomForestClassifier(max_depth=10,min_samples_leaf=50,min_samples_split=2,n_estimators=100)\n",
    "model.fit(train_x,train_y)\n",
    "\n",
    "\n",
    "auc_rf = roc_auc_score(valid_y,model.predict_proba(valid_x)[:,1])\n",
    "print('accuracy：',model.score(valid_x,valid_y))\n",
    "print('roc_auc：',auc_rf)"
   ],
   "id": "8efacfc5e5d7b3ff",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "accuracy： 0.9385314242999252\n",
      "roc_auc： 0.6642755151271035\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-24T03:18:55.635513Z",
     "start_time": "2024-09-24T03:18:52.601188Z"
    }
   },
   "cell_type": "code",
   "source": "prob_lgbm = model.predict_proba(test)[:,1]",
   "id": "3e1b8a25d2897419",
   "outputs": [],
   "execution_count": 21
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-24T03:19:04.102435Z",
     "start_time": "2024-09-24T03:19:04.097429Z"
    }
   },
   "cell_type": "code",
   "source": "prob_lgbm",
   "id": "b20ebde666df1d5",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0.0733965 , 0.06776441, 0.0345905 , ..., 0.03355003, 0.04361679,\n",
       "       0.03562097])"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 22
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-24T03:19:43.425271Z",
     "start_time": "2024-09-24T03:19:42.666596Z"
    }
   },
   "cell_type": "code",
   "source": [
    "submission = pd.DataFrame()\n",
    "submission[['user_id','merchant_id']] = test[['user_id','merchant_id']]\n",
    "submission['prob'] = prob_lgbm\n",
    "submission.to_csv('prediction.csv',index=False)"
   ],
   "id": "afbfb63a527835c4",
   "outputs": [],
   "execution_count": 24
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
